package com.tlxch.server.teacher.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.tlxch.context.BaseContext;
import com.tlxch.dto.StuAvgdto;
import com.tlxch.dto.TScGradedto;
import com.tlxch.dto.TStudto;
import com.tlxch.mapper.SClassMapper;
import com.tlxch.mapper.ScGradesMapper;
import com.tlxch.mapper.TAlertMapper;
import com.tlxch.pojo.SClass;
import com.tlxch.pojo.SStudent;
import com.tlxch.pojo.ScGrades;
import com.tlxch.pojo.TAlert;
import com.tlxch.result.PageResult;
import com.tlxch.server.teacher.TScGradesService;
import com.tlxch.vo.Gradesvo;
import com.tlxch.vo.StuAvgvo;
import com.tlxch.vo.TScGradevo;
import com.tlxch.websocket.WebSocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

import java.util.List;

@Service
public class TScGradesServiceImpl implements TScGradesService {
    @Autowired
    ScGradesMapper scGradesMapper;
    @Autowired
    WebSocketServer webSocketServer;
    @Autowired
    TAlertMapper tAlertMapper;
    @Autowired
    SClassMapper sClassMapper;

    @Transactional
    public void upStuGrade(ScGrades scGrades) {
        if (scGrades.getScgGrade().compareTo(new BigDecimal("60")) < 0 ||
                scGrades.getScgPgrade().compareTo(new BigDecimal("60")) < 0) {
            Long currentId = BaseContext.getCurrentId();
            SClass sClass = sClassMapper.getByscgCid(scGrades.getScgCid());
            String message = "{\"msg\":\""+scGrades.getScgSid() +"同学有成绩低于60分！请及时前往预警记录提醒处理！\"}";
            webSocketServer.sendToClient(message, String.valueOf(currentId));
            TAlert tAlert = new TAlert();
            tAlert.setTaSid(scGrades.getScgSid());
            tAlert.setTaContent(scGrades.getScgSid() +"同学"+sClass.getScName()+"课程成绩低于60分，请及时提醒学生!");
            tAlert.setTaLevel(3);
            tAlert.setTaStatus(1);
            tAlert.setTaCreatetime(LocalDateTime.now());
            tAlert.setTaCount(1);
            tAlert.setTaCid(scGrades.getScgCid());
            tAlertMapper.insertgrade(tAlert);
        }
        scGradesMapper.upStuGradeBystuid(scGrades);
    }

    public PageResult pageQuery(TScGradedto tScGradedto) {
        PageHelper.startPage(tScGradedto.getPage(),tScGradedto.getPageSize());
        //下一条sql进行分页，自动加入limit关键字分页
        Page<TScGradevo> page = scGradesMapper.pageQuery(tScGradedto);
        return new PageResult(page.getTotal(), page.getResult());
    }

    public StuAvgvo getStuAvg(StuAvgdto stuAvgdto) {
        return scGradesMapper.getStuAvg(stuAvgdto);
    }

    public Gradesvo getstuGradeByciAndsid(String sid, String cid) {
        return scGradesMapper.getstuGradeByciAndsid(sid,cid);
    }

}
